package fda.base;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class Range {
	private final List<RangeEntry> entries;

	private Range() {
		entries = new ArrayList<>();
	}

	public Range(DiskFile df) {
		this();
		List<Tuple> block;
		for(int i = 0; i < df.getBlockCount(); i++){
			block = df.getBlock(i, false);
			if(block != null && !block.isEmpty()){
				long min = block.get(0).getKeyValue();
				long max = block.get(block.size() - 1).getKeyValue();
				entries.add(new RangeEntry(min, max));
			}
		}
	}

	
	public void saveToFile(String path) {
		int lineCounter = 1;
		File f = new File(path);
		try {
			if (!f.exists())
				f.createNewFile();

			FileWriter fw = null;
			try {
				fw = new FileWriter(f);
				for (RangeEntry ent : entries) {
					fw.write(String.format("%-7d%s\n", lineCounter++, ent));
				}
			} finally {
				if (fw != null)
					fw.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}

class RangeEntry {
	public final long min;
	public final long max;

	public RangeEntry(long min, long max) {
		this.min = min;
		this.max = max;
	}

	public String toString() {
		return String.format("%-10d%d", min, max);
	}
}